package com.share.tool.devops.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.share.common.utils.DateUtil;
import com.share.tool.devops.dao.SerRegisterMapper;
import com.share.tool.devops.model.po.SerRegister;
import com.share.tool.devops.service.SerRegisterService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class SerRegisterServiceImpl implements SerRegisterService {
    @Autowired
    private SerRegisterMapper serviceRegisterMapper;

    @Override
    public Object init() {
        return serviceRegisterMapper.selectList(new QueryWrapper<>());
    }

    @Override
    public boolean registerAndClearHistory(String ip, String contextPath, String port, String serviceName) {
        //1.计算通用值DISTINCT
        List<Long> list = serviceRegisterMapper.disinctVersion(contextPath, serviceName);
        if (list.size() >= 2) {
            //2.删除历史的值
            long version = list.get(1);
            int a = serviceRegisterMapper.deleteByVersion(contextPath, serviceName, version);
        }

        //3.删除当前已存在的
        int a = serviceRegisterMapper.deleteByIpAndPort(ip, port, serviceName, contextPath);

        //4.插入当前的记录
        SerRegister record = new SerRegister();
        record.setContextPath(contextPath);
        record.setServiceName(serviceName);
        record.setIp(ip);
        record.setPort(port);
        record.setVersion(null);
        record.setCreateTime(new Date());
        serviceRegisterMapper.insert(record);
        return true;
    }

    @Override
    public List<SerRegister> listService(String serviceName, String port, String contextPath) {
        int paramCount = 0;
        QueryWrapper queryWrapper = new QueryWrapper();
        if (StringUtils.isNotBlank(serviceName)) {
            queryWrapper.eq("service_name", serviceName);
            paramCount++;
        }
        if (StringUtils.isNotBlank(contextPath)) {
            queryWrapper.eq("context_path", contextPath);
            paramCount++;
        }
        if (StringUtils.isNotBlank(port)) {
            queryWrapper.eq("port", port);
            paramCount++;
        }
        if (paramCount < 1) {
            throw new RuntimeException("入参异常");
        }
        List<SerRegister> list = serviceRegisterMapper.selectList(queryWrapper);
        return list;
    }

    @Override
    public int updateVersion(long version, String ip, String port, String serviceName, String contextPath) {
        String update = DateUtil.getDateTime();
        return serviceRegisterMapper.updateVersion(version, update, ip, port, serviceName, contextPath);
    }
}
